/**
 * 平台分布柱状图组件
 * 
 * 作用：展示不同平台上舆情数据的分布情况
 * 使用：在首页分析区域展示各平台舆情数量对比
 * 数据：接收包含platform(平台名)和count(数量)属性的数组
 * 特点：使用不同颜色的柱状图展示各平台数据，支持显示具体数值和点击交互
 */

<script setup lang="ts">
import { ref, onMounted, watch, computed, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

// 定义属性
const props = defineProps<{
  data: Array<{
    platform: string,
    count: number
  }>
}>()

// 定义事件
const emit = defineEmits<{
  (e: 'platformStatusChange', platforms: Record<string, boolean>): void
}>()

// 保存平台状态（激活/禁用）
const platformStatus = ref<Record<string, boolean>>({})

// 图表实例
let chart: echarts.ECharts | null = null
const chartContainer = ref<HTMLElement | null>(null)

// 平台控制面板的可见性
const showPlatformControl = ref(false)

// 计算有效的平台列表（经过筛选的）
const activePlatforms = computed(() => {
  // 如果platformStatus为空对象，表示全部平台都是激活的
  if (Object.keys(platformStatus.value).length === 0) {
    return props.data.map(item => item.platform)
  }
  
  // 返回状态为true的平台
  return props.data
    .map(item => item.platform)
    .filter(platform => platformStatus.value[platform] !== false)
})

// 过滤后的数据
const filteredData = computed(() => {
  return props.data.filter(item => 
    platformStatus.value[item.platform] !== false
  )
})

// 初始化平台状态
const initPlatformStatus = () => {
  // 初始化所有平台为激活状态
  const status: Record<string, boolean> = {}
  props.data.forEach(item => {
    status[item.platform] = true
  })
  platformStatus.value = status
}

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return
  
  // 创建图表实例
  chart = echarts.init(chartContainer.value)
  
  // 注册点击事件
  chart.on('click', (params) => {
    const platform = params.name
    togglePlatform(platform)
  })
  
  // 更新图表数据
  updateChart()
  
  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', () => {
    chart?.resize()
  })
}

// 切换平台状态
const togglePlatform = (platform: string) => {
  // 创建一个新对象以避免响应式问题
  const newStatus = { ...platformStatus.value }
  newStatus[platform] = !newStatus[platform]
  
  // 检查是否至少有一个平台是激活的
  const hasActivePlatform = Object.values(newStatus).some(status => status)
  
  if (!hasActivePlatform) {
    ElMessage.warning('至少需要保留一个监控平台')
    return
  }
  
  platformStatus.value = newStatus
  
  // 通知父组件平台状态变化
  emit('platformStatusChange', platformStatus.value)
  
  // 更新图表
  updateChart()
}

// 全选/全不选平台
const selectAllPlatforms = (selected: boolean) => {
  const newStatus = { ...platformStatus.value }
  
  // 如果是取消选择，需要至少保留一个平台
  if (!selected) {
    ElMessage.warning('至少需要保留一个监控平台')
    return
  }
  
  // 更新所有平台状态
  props.data.forEach(item => {
    newStatus[item.platform] = selected
  })
  
  platformStatus.value = newStatus
  
  // 通知父组件平台状态变化
  emit('platformStatusChange', platformStatus.value)
  
  // 更新图表
  updateChart()
}

// 更新图表数据
const updateChart = () => {
  if (!chart) return
  
  // 准备数据
  const platforms = filteredData.value.map(item => item.platform)
  const counts = filteredData.value.map(item => item.count)
  const colors = getGradientColors(filteredData.value.length)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params: any) {
        const item = params[0]
        return `${item.name}<br/>${item.seriesName}: ${item.value}<br/><span style="color: #999; font-size: 12px">点击可切换该平台</span>`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '8%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: platforms,
      axisLabel: {
        interval: 0,
        rotate: 30,
        color: '#666',
        fontSize: 12
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#eee'
        }
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      }
    },
    series: [
      {
        name: '舆情数量',
        type: 'bar',
        data: counts.map((value, index) => ({
          value,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {offset: 0, color: colors[index]}, 
              {offset: 1, color: echarts.color.modifyAlpha(colors[index], 0.7)}
            ]),
            borderRadius: [5, 5, 0, 0]
          }
        })),
        barWidth: '50%',
        label: {
          show: true,
          position: 'top',
          fontSize: 12,
          color: '#666'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0,0,0,0.2)'
          }
        }
      }
    ]
  }
  
  chart.setOption(option)
}

// 生成渐变颜色数组
const getGradientColors = (count: number) => {
  const colors = [
    '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de',
    '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#409EFF'
  ]
  
  // 如果颜色不够，循环使用
  const result = []
  for (let i = 0; i < count; i++) {
    result.push(colors[i % colors.length])
  }
  
  return result
}

// 监听数据变化，更新图表
watch(() => props.data, () => {
  // 初始化平台状态（如果未初始化）
  if (Object.keys(platformStatus.value).length === 0) {
    initPlatformStatus()
  }
  
  // 更新图表
  updateChart()
}, { deep: true })

// 组件挂载时初始化图表
onMounted(() => {
  // 初始化平台状态
  initPlatformStatus()
  
  // 初始化图表
  initChart()
})

// 组件卸载前清理资源
onBeforeUnmount(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
  
  window.removeEventListener('resize', () => {
    chart?.resize()
  })
})
</script>

<template>
  <div class="platform-chart-wrapper">
    <div class="chart-header">
      <h3 class="chart-title">平台分布</h3>
      <div class="chart-actions">
        <el-button 
          type="primary" 
          size="small" 
          text 
          @click="showPlatformControl = !showPlatformControl"
        >
          {{ showPlatformControl ? '隐藏' : '平台筛选' }}
        </el-button>
      </div>
    </div>
    
    <div v-if="showPlatformControl" class="platform-control">
      <div class="platform-control-header">
        <span>平台选择</span>
        <div>
          <el-button type="primary" size="small" text @click="selectAllPlatforms(true)">全选</el-button>
          <el-button type="primary" size="small" text @click="selectAllPlatforms(false)">全不选</el-button>
        </div>
      </div>
      <div class="platform-control-list">
        <el-checkbox 
          v-for="item in props.data" 
          :key="item.platform"
          v-model="platformStatus[item.platform]"
          @change="updateChart"
        >
          {{ item.platform }}
        </el-checkbox>
      </div>
    </div>
    
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<style scoped>
.platform-chart-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  padding: 16px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.chart-container {
  width: 100%;
  height: 280px;
}

.platform-control {
  margin-bottom: 16px;
  padding: 12px;
  background: #f9f9f9;
  border-radius: 4px;
  border: 1px solid #eee;
}

.platform-control-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-weight: 500;
}

.platform-control-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
</style> 